package com.ajiao3.preparedstatement.crud;

import com.bean.Order;
import com.util.JDBCUtil;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.*;


/**
 * 通用的查询表数据
 */
public class OrderForQuery {
    public static void main(String[] args) {
        String sql ="SELECT order_id orderId,order_name orderName,order_date orderDate FROM `order` WHERE order_id=?";
        Order order = orderForQuery(sql, 1);
        System.out.println(order);
    }

    /**
     * 针对于表的字段名与类的属性名不相同的情况
     * 必须声明sql时，使用类的属性名来命名字段的别名
     * @param sql
     * @param args
     * @return
     */

    @Test
    public static Order orderForQuery(String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            //执行
            rs = ps.executeQuery();

            //获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();

            //获取列数
            int columnCount = rsmd.getColumnCount();

            if (rs.next()) {
                Order order = new Order();
                for (int i = 0; i < columnCount; i++) {
                    //获取每个列的值:通过结果集ResultSet
                    Object value = rs.getObject(i + 1);

                    //通过元数据ResultSetMetaData
                    //只能获取列的列名getColumnName
                    //获取列的别名getColumnLabel,如果sql没有设置别名，默认的拿到列名
//                    String columnName = rsmd.getColumnName();
                    String countLabel = rsmd.getColumnLabel(i + 1);

                    //给cust对象指定的columnName属性，赋值为value，通过反射
                    //通过反射去找Customer类中对应columnName列名的属性，然后给他赋值columnvalue
                    Field field = Order.class.getDeclaredField(countLabel);
                    field.setAccessible(true);
                    field.set(order, value);
                }
                return order;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.CloseResource(conn, ps, rs);
        }
        return null;
    }


}
